package com.schoolai.oauth2.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.core.io.ClassPathResource;

import java.io.InputStream;
import java.security.KeyStore;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.proc.SecurityContext;
/**
 * Copyright(C),2019-2025，XX公司
 * FileName:JwtConfig
 * Author:
 * 创建时间：2025/10/20 10:10
 * Description:
 * History:
 * <auth>        <time>       <version>       <desc>
 * 作者          修改时间       版本号         描述
 */
//@Configuration
public class JwtConfig {

    //@Bean
    public KeyStore keyStore() throws Exception {
        KeyStore ks = KeyStore.getInstance("JKS");
        try (InputStream is = new ClassPathResource("oauth2.jks").getInputStream()) {
            ks.load(is, "oauth2".toCharArray()); // 替换为实际密码
        }
        return ks;
    }

    //@Bean
    public RSAPrivateKey privateKey(KeyStore keyStore) throws Exception {
        return (RSAPrivateKey) keyStore.getKey("oauth2", "oauth2".toCharArray());
    }

    //@Bean
    public RSAPublicKey publicKey(KeyStore keyStore) throws Exception {
        return (RSAPublicKey) keyStore.getCertificate("oauth2").getPublicKey();
    }

   // @Bean
    public JwtEncoder jwtEncoder(RSAPublicKey publicKey, RSAPrivateKey privateKey) {
        RSAKey rsaKey = new RSAKey.Builder(publicKey)
                .privateKey(privateKey)
                .build();
        JWKSet jwkSet = new JWKSet(rsaKey);
        return new NimbusJwtEncoder(new ImmutableJWKSet<>(jwkSet));
    }

    //@Bean
    public JwtDecoder jwtDecoder(RSAPublicKey publicKey) {
        return NimbusJwtDecoder.withPublicKey(publicKey).build();
    }
}
